package zhtt03.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import zhtt03.entity.User03;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by zhtt on 2016/10/30.
 */
@Service
public class User03Service {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public User03 findById(long id){
        return (User03) jdbcTemplate.queryForObject("select * from zhtt_users where id =? ",new Object[]{id},
                new RowMapper(){
                    @Override
                    public Object mapRow(ResultSet rs, int rowNum)throws SQLException {
                        User03 user  = new User03();
                        user.setId(rs.getLong("id"));
                        user.setName(rs.getString("name"));
                        user.setEmail(rs.getString("email"));
                        java.sql.Date sqlDate=rs.getDate("create_Time");
                        if(sqlDate==null){
                            user.setCreateTime(null);
                        }else{
                            user.setCreateTime(new java.util.Date (sqlDate.getTime()));
                        }
                        return user;
                    }
                }
        );
    }

    /**
     * 保存
     * @param name
     * @param email
     */
    public void save(String name,String email){
        jdbcTemplate.update("insert into zhtt_users( name,email,create_time) values(?,?,?)",  new Object[]{name,email,new Date()});
    }

    /**
     * 更新
     * @param id
     * @param name
     * @param email
     * @return
     */
    public User03 update(final int id,final String name,final String email){
        jdbcTemplate.update(
                "update zhtt_users set name=?,email=? ,create_time=? where id = ?",
                new PreparedStatementSetter(){
                    @Override
                    public void setValues(PreparedStatement ps) throws SQLException {
                        ps.setString(1, name);
                        ps.setString(2, email);
                        ps.setDate(3, new java.sql.Date(new Date().getTime()));
                        ps.setInt(4, id);
                    }
                }
        );
        return null;
    }
}
